<template>
  <div class="departments">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索部门名称"
            clearable
            @clear="handleSearch"
            @keyup.enter.native="handleSearch">
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
          </el-input>
        </el-col>
        <el-col :span="18" style="text-align: right">
          <el-button type="primary" @click="handleAdd">新增部门</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 部门列表 -->
    <el-table
      v-loading="loading"
      :data="departments"
      border
      style="width: 100%">
      <el-table-column prop="name" label="部门名称" width="180"></el-table-column>
      <el-table-column prop="description" label="部门描述"></el-table-column>
      <el-table-column prop="employee_count" label="员工数量" width="120">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.employee_count }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            :disabled="scope.row.employee_count > 0">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 部门表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      @close="resetForm">
      <el-form
        ref="departmentForm"
        :model="departmentForm"
        :rules="rules"
        label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="departmentForm.name"></el-input>
        </el-form-item>
        <el-form-item label="部门描述" prop="description">
          <el-input
            type="textarea"
            v-model="departmentForm.description"
            :rows="3">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Departments',
  data() {
    return {
      // 表格数据
      departments: [],
      loading: false,
      searchQuery: '',

      // 对话框
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      submitting: false,
      departmentForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchDepartments()
  },
  methods: {
    // 获取部门列表
    async fetchDepartments() {
      this.loading = true
      try {
        const response = await axios.get('/api/departments/')
        this.departments = response.data
      } catch (error) {
        this.$message.error('获取部门列表失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      if (this.searchQuery) {
        this.departments = this.departments.filter(dept =>
          dept.name.toLowerCase().includes(this.searchQuery.toLowerCase())
        )
      } else {
        this.fetchDepartments()
      }
    },

    // 新增部门
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增部门'
      this.dialogVisible = true
    },

    // 编辑部门
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑部门'
      this.departmentForm = { ...row }
      this.dialogVisible = true
    },

    // 删除部门
    handleDelete(row) {
      this.$confirm('确认删除该部门吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await axios.delete(`/api/departments/${row.id}/`)
          this.$message.success('删除成功')
          this.fetchDepartments()
        } catch (error) {
          this.$message.error(error.response?.data?.error || '删除失败')
        }
      }).catch(() => {})
    },

    // 提交表单
    submitForm() {
      this.$refs.departmentForm.validate(async valid => {
        if (valid) {
          this.submitting = true
          try {
            if (this.isEdit) {
              await axios.put(`/api/departments/${this.departmentForm.id}/`, this.departmentForm)
              this.$message.success('更新成功')
            } else {
              await axios.post('/api/departments/', this.departmentForm)
              this.$message.success('创建成功')
            }
            this.dialogVisible = false
            this.fetchDepartments()
          } catch (error) {
            this.$message.error(error.response?.data?.error || '操作失败')
          } finally {
            this.submitting = false
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      this.$refs.departmentForm?.resetFields()
      this.departmentForm = {
        name: '',
        description: ''
      }
    }
  }
}
</script>

<style scoped>
.departments {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}
</style> 